package server.web;

import java.util.Iterator;
import java.util.Vector;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;

import server.Main;
import server.web.api.Test;
import server.web.api.webuser.Heartbeat;
import server.web.api.webuser.Login;
import server.web.api.webuser.Query;
import server.web.api.webuser.SendMsg;

public class HttpServer {
    public static final int HEARTBEAT_TIMEOUT = 15 * 1000; // 心跳连接超过十五秒记为断开连接

    private final Server _httpServer;
    private final ServletContextHandler _handlers;

    private static final Vector<WebUser> _users = new Vector<>();

    public HttpServer(int port) {
        _httpServer = new Server(port);
        _handlers   = new ServletContextHandler(ServletContextHandler.SESSIONS);
        
        _httpServer.setStopAtShutdown(true);
    }

    // 用网页静态文件所在的目录作为参数，开启HTTP服务器
    public void start(String httpPath) {
        _handlers.setContextPath("/");
        _handlers.setResourceBase(httpPath);
        _handlers.setWelcomeFiles(new String[] { "index.html" });
        _handlers.addServlet(DefaultServlet.class, "/");
        loadApis();

        _httpServer.setHandler(_handlers);
        System.out.println("【HTTP服务器】 以下为Jetty启动日志！");
        try {
            _httpServer.start();
        } catch (Exception e) {
            System.out.println("【HTTP服务器】 Jetty服务器启动失败！");
            return;
        }
        System.out.println("【HTTP服务器】 Jetty服务器启动成功！");

        while (true) {
            Iterator<WebUser> i = _users.iterator();
            try {
                while (i.hasNext()) {
                    WebUser webUser = i.next();
                    if (webUser.isDead()) {
                        System.out.println("【HTTP服务器】 用户【" + webUser.getName() + "】已断开连接！");
                        Main.chatServer.clientList.remove(webUser);
                        i.remove();
                    }
                }
            } catch (Exception ignored) {}
        }
    }

    public static WebUser createWebUser(String name, long uid) {
        WebUser u = new WebUser(name, uid);
        _users.add(u);
        Main.chatServer.clientList.add(u);
        u.heartbeat();
        Main.chatServer.sendMsg("【系统消息】 Web端用户" + u.getName() + "已经连接至服务器");
        System.out.println("【HTTP服务器】 新的连接已建立");
        return u;
    }

    //合并Http线程和主线程
    public void join() throws InterruptedException {
        if (_httpServer.isRunning()) {
            _httpServer.join();
        }
    }

    private void loadApis() {
        _handlers.addServlet(Test.class, "/getnum");
        _handlers.addServlet(Login.class, "/webuser/login");
        _handlers.addServlet(Heartbeat.class, "/webuser/heartbeat");
        _handlers.addServlet(Query.class, "/webuser/query");
        _handlers.addServlet(SendMsg.class, "/webuser/send");
    }
}